package cn.kgc.chlm.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 作为接触的Servlet使用继承HttpServlet
 * 同时重写HttpServlet类的service(HttpServletRequest req, HttpServletResponse resp)方法
 */
//@WebServlet("/base")
public class BaseServlet extends HttpServlet {
//    @Override
//    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
//        HttpServletRequest request = (HttpServletRequest) req;
//        System.out.println(request.getMethod());
//    }

    /**
     * 这个放法是那个子类被调用，就是那个那个子类的service方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //验证当前对象是哪个对像
        //System.out.println(this);

        //查看当前对象都有什么public 方法
//        Method[] methods = this.getClass().getMethods();
//        System.out.println(Arrays.toString(methods));

        //获取当前访问路径
        String requestURI = req.getRequestURI();
        //System.out.println(requestURI);
        //我们要获取一个方法名
        String methodName = requestURI.substring(requestURI.lastIndexOf("/")+1);
        //System.out.println(methodName);


        try {
            //根据方法名和参数获取方法对象
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //执行方法
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }
}

